<?php
namespace app\api\controller;

use app\BaseController;
use think\facade\Db;

class Test extends BaseController
{
    /**
     * 获取某个测试的所有题目
     * GET /api/test/:typeId/questions
     */
    public function getQuestions($typeId)
    {
        $questions = Db::name('question')
            ->where('test_type_id', $typeId)
            ->order('sort')
            ->field('id, content, options')
            ->select()
            ->toArray();

        if (empty($questions)) {
            return json(['code' => 404, 'msg' => '测试题不存在']);
        }

        // 记录开始测试（创建记录）
        $recordId = Db::name('test_record')->insertGetId([
            'user_id' => $this->request->uid,
            'test_type_id' => $typeId,
            'start_time' => date('Y-m-d H:i:s'),
            'status' => 'started'
        ]);

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'record_id' => $recordId,
                'questions' => $questions
            ]
        ]);
    }

    /**
     * 提交测试答案
     * POST /api/test/submit
     */
    public function submitAnswer()
    {
        $data = $this->request->post();
        $recordId = $data['record_id'];
        $answers = $data['answers']; // [{question_id: 1, answer: 5}, ...]

        $userId = $this->request->uid;

        // 校验 record_id 是否属于该用户
        $record = Db::name('test_record')->where([
            ['id', '=', $recordId],
            ['user_id', '=', $userId]
        ])->find();

        if (!$record) {
            return json(['code' => 403, 'msg' => '无权提交']);
        }

        $totalScore = 0;
        $dimensions = [];

        foreach ($answers as $item) {
            $question = Db::name('question')->field('score_type, dimension')->find($item['question_id']);
            if (!$question) continue;

            Db::name('answer')->insert([
                'record_id' => $recordId,
                'question_id' => $item['question_id'],
                'answer_value' => $item['answer'],
                'create_time' => date('Y-m-d H:i:s')
            ]);

            // 累计分数
            $totalScore += $item['answer'];

            // 处理人格维度（如MBTI）
            if ($question['dimension']) {
                $dimensions[$question['dimension']] = ($dimensions[$question['dimension']] ?? 0) + $item['answer'];
            }
        }

        // 生成结果（简化版）
        $resultText = $this->generateResult($record['test_type_id'], $totalScore, $dimensions);

        Db::name('test_record')->where('id', $recordId)->update([
            'end_time' => date('Y-m-d H:i:s'),
            'score_result' => json_encode([
                'total' => $totalScore,
                'dimensions' => $dimensions
            ]),
            'result_text' => $resultText,
            'status' => 'completed'
        ]);

        return json([
            'code' => 200,
            'msg' => '提交成功',
            'data' => [
                'result_text' => $resultText,
                'score' => $totalScore,
                'dimensions' => $dimensions
            ]
        ]);
    }

    private function generateResult($testTypeId, $totalScore, $dimensions)
    {
        // 这里根据 testTypeId 和逻辑生成结果
        // 我们稍后提供示例
        return "您的测试已完成，总分为 {$totalScore}。";
    }
}